﻿using SSCAI.Model;
using SSCAI.Client.ViewModels;
using SSCAI.Common;
using SSCAI.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Threading;
using SSCAI.Filter;
using System.IO;
using Microsoft.Win32;
using System.Windows.Media;
using System.Xml;
using System.Xml.Linq;

namespace SSCAI.Client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private int timeSpan = 600;

        DispatcherTimer dispatcherTimer;
        DispatcherTimer countdownTimer;
        DispatcherTimer initDataTimer;

        MainWindowsViewModel vm = null;
        private bool updateState = false;
        private bool isAdded = false;
        private Countdown countdown = new Countdown();

        private static bool threadStates = false;

        private static string path = string.Empty;

        private static FilterModel filterModel = new FilterModel();

        private static List<List<LotteryModel>> testData = null;

        private static int testCount = 120;
        private static int rightCount = 0;

        private static int winCount = 0; // 总奖金
        private static int costCount = 0; //总花费

        private static int solution = 0;

        public MainWindow()
        {
            InitializeComponent();


            for (int i = 0; i <= 500; i++)
            {
                this.cmb012.Items.Add(i);
            }

            this.cmb012.SelectedIndex = 0;

            for (int i = 0; i <= 500; i++)
            {
                this.cmb0123.Items.Add(i);
            }
            this.cmb0123.SelectedIndex = 0;
            for (int i = 0; i <= 500; i++)
            {
                this.cmb01234.Items.Add(i);
            }

            this.pbLotterys.Maximum = 15;
            this.pbLotterys.Value = 0;

            this.cmb01234.SelectedIndex = 0;

            this.GetTimeSpan();
            this.btnGenerateDatas.IsEnabled = false;
            ThreadPool.QueueUserWorkItem(q => { this.CorrectCountdownTimer(); });

            ThreadPool.QueueUserWorkItem(q =>
            {
                XmlHelper.UpdateAllData(50);//期数
                this.updateState = true;

            });

            ThreadPool.QueueUserWorkItem(q =>
            {
                while (!this.updateState)
                {
                    Thread.Sleep(400);
                    this.pbLotterys.Dispatcher.Invoke(new Action(delegate()
                    {
                        this.pbLotterys.Value = XmlHelper.LoopCount + 1;
                    }));
                }
            });

            InicializeDispatcherTimer();


        }

        private void CorrectCountdownTimer()
        {
            DateTime lDate = DateTime.Now;
            countdown.TotalSeconds = timeSpan - (lDate.Minute % (this.timeSpan / 60)) * 60 - lDate.Second;
            this.isAdded = false;
        }

        private void GetTimeSpan()
        {
            var nowTime = DateTime.Now;
            if (nowTime.Hour >= 22 || nowTime.Hour <= 2)
            {
                this.timeSpan = 300;
            }
            else
            {
                this.timeSpan = 600;
            }
        }

        /// <summary>
        /// 初始化定时器
        /// </summary>
        void InicializeDispatcherTimer()
        {
            dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Tick += dispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
            dispatcherTimer.Start();

            countdownTimer = new DispatcherTimer();
            countdownTimer.Tick += countdownTimer_Tick;
            countdownTimer.Interval = new TimeSpan(0, 0, 1);
            countdownTimer.Start();

            initDataTimer = new DispatcherTimer();
            initDataTimer.Tick += initDataTimer_Tick;
            initDataTimer.Interval = new TimeSpan(0, 0, 2);
            initDataTimer.Start();
        }

        private void initDataTimer_Tick(object sender, EventArgs e)
        {
            if (this.updateState)
            {
                vm = new MainWindowsViewModel();
                //this.DataContext = vm;

                this.dgLottery.Dispatcher.Invoke(new Action(delegate() { this.dgLottery.ItemsSource = vm.LotterysProperty; }));
                this.btnGenerateDatas.IsEnabled = true;
                this.rdbSecondSolution.IsChecked = true;
                initDataTimer.Stop();
            }
        }

        private void countdownTimer_Tick(object sender, EventArgs e)
        {
            this.GetTimeSpan();

            if (countdown.TotalSeconds == 0)
            {
                this.CorrectCountdownTimer();
            }

            txtCountdown.Text = string.Concat(countdown.Minutes.ToString("00"), " : ", countdown.Seconds.ToString("00"));
            countdown.TotalSeconds--;

        }

        void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            if (this.updateState && !this.isAdded)
            {
                if (countdown.Minutes > (timeSpan / 60) - 2)
                {
                    XmlHelper.AddOneItem(out this.isAdded);

                    if (this.isAdded)
                    {
                        LotteryData.ClearInstance();

                        this.dgLottery.Dispatcher.Invoke(new Action(delegate() { this.dgLottery.ItemsSource = LotteryData.GetInstance().Lotterys; }));

                        //Display winner number
                        DisplayResult();
                    }
                }

            }
        }

        private void btnGenerateDatas_Click_1(object sender, RoutedEventArgs e)
        {
            #region Generating data

            this.ClearFilterThreadsState();
            this.btnGenerateDatas.IsEnabled = false;
            lblDataCount.Content = "正在生成数据......";
            this.txtTestData.Text = string.Empty;
            FilterHelper.dataSource = new List<LotteryModel>();
            foreach (var l in LotteryData.GetInstance().Lotterys)
            {
                FilterHelper.dataSource.Add(l);
            }

            //取得当前期号码
            var issue = LotteryData.GetInstance().Lotterys.FirstOrDefault().Issue;

            //var currentDate = "20" + issue.Substring(0, 2) + "-" + issue.Substring(2, 2) + "-" + issue.Substring(4, 2);
            //if (SSCAI.Common.CalculateHelper.ExpiredDate < Convert.ToDateTime(currentDate))
            //{
            //    MessageBox.Show("软件过期！");
            //    return;
            //}

            this.progressBar.Minimum = 0;
            this.progressBar.Maximum = testCount;
            this.progressBar.Value = 0;
            rightCount = 0;
            winCount = 0;
            costCount = 0;
            this.InitFilterModel();

            List<List<LotteryModel>> data = this.GetFilterData();

            this.CorrectCountdownTimer();

            ThreadPool.QueueUserWorkItem(q =>
            {
                while (true)
                {
                    if (this.IsFilterThreadsReady())
                    {
                        var allData = new List<LotteryModel>();
                        foreach (var d in data)
                        {
                            allData.AddRange(d);
                        }

                        var nextIssue = issue.Substring(0, issue.Length - 3) + (Convert.ToInt32(issue.Substring(issue.Length - 3, 3)) + 1).ToString("000");
                        string strCount = string.Format("第" + nextIssue + "期" + " 生成{0}注", allData.Count);
                        var lotteries = allData.Select(d => d.FourDNumber).OrderBy(n => n).ToArray();
                        var generateDatas = string.Join(",", lotteries);

                        SetAverageDatasToEachTextBox(generateDatas, strCount);

                        //SSCaiService.SSCaiService sc = new SSCaiService.SSCaiService();
                        //var nextIssue = issue.Substring(0, issue.Length - 3) + (Convert.ToInt32(issue.Substring(issue.Length - 3, 3)) + 1).ToString("000");
                        //sc.SetLotteries(HistoricDataHelper.SolutionId=="A"?0:1, lotteries, nextIssue);

                        break;
                    }

                }
            });

            #endregion

            #region Update history

            ThreadPool.QueueUserWorkItem(q =>
            {
                int counter = 0;
                var lastLottery = new LotteryModel();
                List<KeyValuePair<LotteryModel, List<LotteryModel>>> allTestData = new List<KeyValuePair<LotteryModel, List<LotteryModel>>>();
                Int64 spanIssues = 0;
                XDocument doc = HistoricDataHelper.LoadXmlFile();
                XNode lastNode = doc.Root.LastNode;
                if (!HistoricDataHelper.IsEmptyFile())
                {
                    var lastIssue = HistoricDataHelper.GetLastIssue();
                    var currentIssue = LotteryData.GetInstance().Lotterys.FirstOrDefault().Issue;
                    spanIssues = Convert.ToInt64(currentIssue) - Convert.ToInt64(lastIssue);
                }
                else
                {
                    spanIssues = -1;
                }

                if (spanIssues == 0) goto ReadHistory;

                while (true)
                {
                    if (this.IsFilterThreadsReady())
                    {
                        if (null != testData)
                        {
                            List<LotteryModel> list = new List<LotteryModel>();
                            foreach (var d in testData)
                            {
                                list.AddRange(d);
                            }

                            if (list.Where(l => l.FourDNumber == lastLottery.FourDNumber).Count() == 1)
                            {
                                lastLottery.IsValid = true;
                                rightCount++;
                            }

                            if (spanIssues == -1)
                            {//+ "-" + FilterHelper.maxWeiHotCodes
                                HistoricDataHelper.InsertLottery(lastLottery.Issue, lastLottery.FourDNumber, list.Count.ToString(), lastLottery.IsValid ? "y" : "n");
                            }
                            else if (spanIssues >= 1)
                            {//+ "-" + FilterHelper.maxWeiHotCodes
                                HistoricDataHelper.InsertLottery(doc, lastNode, lastLottery.Issue, lastLottery.FourDNumber, list.Count.ToString(), lastLottery.IsValid ? "y" : "n");
                                spanIssues--;
                                if (spanIssues < 1)
                                {
                                    break;
                                }
                            }

                            this.txtTestData.Dispatcher.Invoke(new Action(delegate()
                            {
                                this.txtTestData.Text += lastLottery.Issue + "开 " + lastLottery.FourDNumber + (lastLottery.IsValid ? " 中奖" : " 未中奖") + "，生成" + list.Count() + "注\r\n";

                                costCount += list.Count() * 2 / 10;

                                if (lastLottery.IsValid)
                                {
                                    winCount += 1910;
                                }

                            }));

                            this.progressBar.Dispatcher.Invoke(new Action(delegate()
                            {
                                this.progressBar.Value = counter;
                            }));

                            this.txtRate.Dispatcher.Invoke(new Action(delegate()
                            {
                                //double rate = (double)rightCount * 100.00 / (double)counter;
                                //var temp = "    中奖率：" + rate.ToString("f2") + "%       " + "            花" + costCount + " 赚" + winCount + "  赚：" + (winCount - costCount);
                                this.txtRate.Text = "购买次数 ： " + counter + "赚：" + (winCount - costCount);//v1
                                //this.txtRate.Text = "购买次数 ： " + counter;//v2
                            }));

                        }

                        if (counter > testCount - 1)
                        {
                            this.btnGenerateDatas.Dispatcher.Invoke(new Action(delegate() { this.btnGenerateDatas.IsEnabled = true; }));
                            break;
                        }

                        lastLottery = FilterHelper.dataSource.Take(1).Select(l => new LotteryModel { Id = l.Id, Issue = l.Issue, IsValid = l.IsValid, WinningNumber = l.WinningNumber }).First();
                        FilterHelper.dataSource.RemoveAt(0);

                        testData = this.GetFilterData();

                        counter++;
                    }
                }

            ReadHistory:

                this.txtTestData.Dispatcher.Invoke(new Action(delegate()
                {
                    this.txtTestData.Text = "";
                }));

                var historicList = HistoricData.GetHistoricData();
                this.progressBar.Dispatcher.Invoke(new Action(delegate()
                {
                    this.progressBar.Maximum = historicList.Count();
                }));

                counter = 0;
                costCount = 0;
                winCount = 0;
                rightCount = 0;
                foreach (var h in historicList)
                {
                    this.txtTestData.Dispatcher.Invoke(new Action(delegate()
                    {
                        this.txtTestData.Text += h.Issue + "开 " + h.Number4D + (h.IsCorrect ? " 中奖" : " 未中奖") + "，生成" + h.count + "注\r\n";
                    }));

                    this.progressBar.Dispatcher.Invoke(new Action(delegate()
                    {
                        this.progressBar.Value = ++counter;
                    }));

                    costCount += h.count * 2 / 10;

                    if (h.IsCorrect)
                    {
                        winCount += 1910;
                        rightCount++;
                    }

                    this.txtRate.Dispatcher.Invoke(new Action(delegate()
                    {
                        //double rate = (double)rightCount * 100.00 / (double)counter;
                        //var temp = "    中奖率：" + rate.ToString("f2") + "%       " + "            花" + costCount + " 赚" + winCount + " 利：" + (winCount - costCount);
                        this.txtRate.Text = "购买次数 ： " + counter + " 利：" + (winCount - costCount);//v1
                       // this.txtRate.Text = "购买次数 ： " + counter;//v1
                    }));
                }

                this.btnGenerateDatas.Dispatcher.Invoke(new Action(delegate()
                {
                    while (true)
                    {
                        if (this.IsFilterThreadsReady())
                        {
                            this.btnGenerateDatas.IsEnabled = true;
                            break;
                        }
                    }

                }));
            });

            #endregion
        }

        private List<List<LotteryModel>> GetFilterData()
        {
            this.ClearFilterThreadsState();
            FilterDelegate filters = this.GetFiters();
            List<List<LotteryModel>> data = new List<List<LotteryModel>>();
            ThreadPool.QueueUserWorkItem(q =>
            {
                List<LotteryModel> d1 = new List<LotteryModel>();
                for (int i = 9999; i > -1; i--)
                {
                    FilterHelper.KillCounter = 0;
                    LotteryModel d = new LotteryModel() { WinningNumber = i.ToString("00000"), IsValid = true };

                    filters(d);
                    #region v1
                    if (solution == 0)//方案一
                    {
                        if (FilterHelper.KillCounter < 2)//if (d.IsValid)
                        {
                            d1.Add(d);
                        }
                    }
                    if (solution == 1)//方案二
                    {
                        if (FilterHelper.KillCounter < 1)//if (d.IsValid)
                        {
                            d1.Add(d);
                        }
                    }
                    if (solution == 2)//方案三
                    {
                        if (FilterHelper.KillCounter > 1)//if (d.IsValid)
                        {
                            d1.Add(d);
                        }
                    }
                    #endregion

                    #region v2
                    ////方案一二三都是使用 V1 的方案三
                    //if (FilterHelper.KillCounter >= 1)//if (d.IsValid)
                    //{
                    //    d1.Add(d);
                    //}

                    #endregion

                }

                data.Add(d1);
                threadStates = true;
            });

            return data;
        }

        private bool IsFilterThreadsReady()
        {
            return threadStates;
        }

        private void ClearFilterThreadsState()
        {
            testData = null;
            threadStates = false;
        }

        private void btnExportDatas_Click_1(object sender, RoutedEventArgs e)
        {
            //this.txtGeneratedData.IsEnabled = false;
            //if (string.IsNullOrEmpty(this.txtGeneratedData.Text.Trim())) return;

            //SaveFileDialog dialog = new SaveFileDialog();
            //dialog.Title = "导出生成的投注数据";
            //var now = DateTime.Now;
            //dialog.FileName = "投注数据" + now.Year + now.Month + now.Day + now.Hour + now.Minute + now.Second;
            //dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            //dialog.RestoreDirectory = true;
            //if (dialog.ShowDialog() == true)
            //{
            //    File.WriteAllText(dialog.FileName, this.txtGeneratedData.Text.Trim());
            //}

            //string fileName = "ExportDatas.txt";
            //string filePath = AppDomain.CurrentDomain.BaseDirectory;
            //path = filePath + fileName;
            ////创建并写入(将覆盖已有文件)
            //if (!File.Exists(filePath + fileName))
            //{
            //    using (FileStream stream = File.Create(path))
            //    { }
            //}

            //// Create a file to write to.
            //using (StreamWriter sw = File.CreateText(path))
            //{
            //    sw.WriteLine(this.txtGeneratedData.Text.Trim());
            //}

            ////MessageBox.Show("数据已导出", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            ////this.tbResult.Text = "在" + DateTime.Now + " 已导出数据，等待开奖...";

            //this.txtGeneratedData.IsEnabled = true;
        }

        private void InitFilterModel()
        {
            filterModel.IsKillBaozi = Convert.ToBoolean(this.chbDengZhi.IsChecked);
            filterModel.IsKillDanMa = Convert.ToBoolean(this.chbDanMa.IsChecked);
            filterModel.IsKillHeZhi = Convert.ToBoolean(this.chbHeZhi.IsChecked);
            filterModel.IsKillKuaDuHe = Convert.ToBoolean(this.chbKuaDuHe.IsChecked);
            filterModel.IsKillSameSpan = Convert.ToBoolean(this.chbXiangTongKuaDu.IsChecked);
            filterModel.IsKillShunZiSpan = Convert.ToBoolean(this.chbShunZhiKuaDu.IsChecked);
            filterModel.IsKillLast200 = Convert.ToBoolean(this.chbQian200.IsChecked);
            filterModel.IsKillLastIssue = Convert.ToBoolean(this.chbLatestIssue.IsChecked);

            filterModel.IsKillEveryWeiCool = Convert.ToBoolean(this.chbZuiLengHao.IsChecked);
            filterModel.IsKillEveryWeiHot = Convert.ToBoolean(this.chbHotCode.IsChecked);
            filterModel.IsKillShunZi = Convert.ToBoolean(this.chkShunzi.IsChecked);
            filterModel.IsKill0123 = Convert.ToBoolean(this.chk0123.IsChecked);
            filterModel.IsKill012 = Convert.ToBoolean(this.chk012.IsChecked);
            filterModel.IsKill0123 = Convert.ToBoolean(this.chk0123.IsChecked);
            filterModel.IsKill01234 = Convert.ToBoolean(this.chk01234.IsChecked);
            //filterModel.IsKillTwoTwoGroup = Convert.ToBoolean(this.chbTwoTwoGroup.IsChecked);
            filterModel.IsKillPositionDifference = Convert.ToBoolean(this.chbPositionDifference.IsChecked);

            FilterHelper.kill012Count = Convert.ToInt16(this.cmb012.Text);
            FilterHelper.kill0123Count = Convert.ToInt16(this.cmb0123.Text);
            FilterHelper.kill01234Count = Convert.ToInt16(this.cmb01234.Text);

            filterModel.IsKillBigToSmall = Convert.ToBoolean(this.chbBigToSmall.IsChecked);
            filterModel.IsKillSmallToBig = Convert.ToBoolean(this.chbSmallToBig.IsChecked);

            filterModel.IsKillProduct = Convert.ToBoolean(this.chbProduct.IsChecked);

            filterModel.IsKillHouShanDanMa = Convert.ToBoolean(this.chbHSDanMa.IsChecked);
            filterModel.IsKillSmallMiddleBig = Convert.ToBoolean(this.chbSmallMiddleBig.IsChecked);

            filterModel.IsKillSQSWDanMa = Convert.ToBoolean(this.chbSQSWDanMa.IsChecked);
            filterModel.IsKillHouShanDanMa3 = Convert.ToBoolean(this.chbHSDanMa3.IsChecked);

            filterModel.IsKillLastTwoNumsSum = Convert.ToBoolean(this.chbLastTwoNumsSum.IsChecked);
            filterModel.IsKillLastTwoNumsSubstraction = Convert.ToBoolean(this.chbLastTwoNumsSubtraction.IsChecked);
        }

        private FilterDelegate GetFiters()
        {
            FilterHelper.LastLottery = FilterHelper.dataSource.FirstOrDefault();
            FilterHelper.LastTwoLotterys = FilterHelper.dataSource.Take(2).ToList();
            FilterHelper.LastFourLotterys = FilterHelper.dataSource.Take(4).ToList();

            FilterDelegate filters = new FilterDelegate(FilterHelper.FilterNothing);
            //filters += new FilterDelegate(FilterHelper.KillSumTail);

            //杀豹子
            if (filterModel.IsKillBaozi) filters += new FilterDelegate(FilterHelper.KillLoepardData);

            //杀上期和值
            if (filterModel.IsKillHeZhi) filters += new FilterDelegate(FilterHelper.KillSumData);
            //杀跨度和
            if (filterModel.IsKillKuaDuHe) filters += new FilterDelegate(FilterHelper.KillKuaDuHe);

            //啥相同跨度
            if (filterModel.IsKillSameSpan) filters += new FilterDelegate(FilterHelper.KillXiangTongKuaDu);
            //杀顺子跨度
            if (filterModel.IsKillShunZiSpan) filters += new FilterDelegate(FilterHelper.KillShunZiKuaDu);
            //杀前200期
            if (filterModel.IsKillLast200)
            {
                FilterHelper.LastNLotterys = FilterHelper.SelectedSolution == 1 ? 50 : 200;

                FilterHelper.Last200Lotterys = FilterHelper.dataSource.Take(FilterHelper.LastNLotterys).Select(d => d.FourDNumber).ToList();
                filters += new FilterDelegate(FilterHelper.KillQian200);
            }
            //杀上期开奖号码
            if (filterModel.IsKillLastIssue)
            {
                filters += new FilterDelegate(FilterHelper.KillShangQiKaiJiangHaoMa);
            }

            if (filterModel.IsKillSmallToBig)
            {
                filters += new FilterDelegate(FilterHelper.KillSmallToBig);
            }

            if (filterModel.IsKillBigToSmall)
            {
                filters += new FilterDelegate(FilterHelper.KillBigToSmall);
            }

            //杀顺子:1234,2345...
            if (filterModel.IsKillShunZi)
            {
                filters += new FilterDelegate(FilterHelper.KillShunZi);
            }

            if (filterModel.IsKill012)
            {
                FilterHelper.Last012Number = FilterHelper.dataSource.Take(FilterHelper.kill012Count).Select(l => l.Number012).ToList();
                filters += new FilterDelegate(FilterHelper.Kill012);
            }

            if (filterModel.IsKill0123)
            {
                FilterHelper.Last0123Number = FilterHelper.dataSource.Take(FilterHelper.kill0123Count).Select(l => l.Number0123).ToList();
                filters += new FilterDelegate(FilterHelper.Kill0123);
            }

            if (filterModel.IsKill01234)
            {
                FilterHelper.Last01234Number = FilterHelper.dataSource.Take(FilterHelper.kill01234Count).Select(l => l.Number01234).ToList();
                filters += new FilterDelegate(FilterHelper.Kill01234);
            }

            //过滤胆码
            if (filterModel.IsKillDanMa)
            {
                var latestLottery = FilterHelper.dataSource.FirstOrDefault();
                FilterHelper.latestDanMaIndex = Math.Abs(latestLottery.GeWei - latestLottery.ShiWei);
                filters += new FilterDelegate(FilterHelper.DanMa);
            }

            // 过滤位最冷码
            if (filterModel.IsKillEveryWeiCool)
            {
                FilterHelper.maxWeiCoolCodes = FilterHelper.GetWeiCoolCodes();
                filters += new FilterDelegate(FilterHelper.KillEveryWeiZuiLengHao);
            }

            // 过滤位最冷码
            if (filterModel.IsKillEveryWeiHot)
            {
                FilterHelper.maxWeiHotCodes = FilterHelper.GetWeiHotCodes();
                filters += new FilterDelegate(FilterHelper.KillEveryWeiZuiReHao);
            }

            //过滤乘积
            if (filterModel.IsKillProduct)
            {
                if (FilterHelper.SelectedSolution == 1)//方案二
                {
                    FilterHelper.LatestOneHundredProduct = FilterHelper.dataSource.Take(1).Select(d => d.Product).ToList();
                }
                else//方案一 or 三
                {
                    FilterHelper.LatestOneHundredProduct = FilterHelper.dataSource.Take(10).Select(d => d.Product).ToList();
                }
                filters += new FilterDelegate(FilterHelper.KillProduct);
            }

            //过滤位差
            if (filterModel.IsKillPositionDifference)
            {
                if (FilterHelper.SelectedSolution == 1)
                {
                    FilterHelper.LatestOneHundredPositionDifference = FilterHelper.dataSource.Take(3).Select(d => d.FourDDeviation).ToList();
                }
                else
                {
                    FilterHelper.LatestOneHundredPositionDifference = FilterHelper.dataSource.Take(10).Select(d => d.FourDDeviation).ToList();
                }

                filters += new FilterDelegate(FilterHelper.KillPositionDifference);
            }

            //过滤上期后三位胆码
            if (filterModel.IsKillHouShanDanMa)
            {
                filters += new FilterDelegate(FilterHelper.KillShangQiHouShanDanMa);
            }

            //其它3组胆码
            if (filterModel.IsKillHouShanDanMa3)
            {
                filters += new FilterDelegate(FilterHelper.KillShangQiHouShanDanMa3);
            }


            //过滤上期小中大号
            if (filterModel.IsKillSmallMiddleBig)
            {
                filters += new FilterDelegate(FilterHelper.KillShangQiSmallMiddleBig);
            }

            //后四位胆码
            if (filterModel.IsKillSQSWDanMa)
            {
                filters += new FilterDelegate(FilterHelper.KillShangQiSiDanMa);
            }

            if (filterModel.IsKillLastTwoNumsSubstraction)
            {
                filters += new FilterDelegate(FilterHelper.KillLastTwoNumsSubtraction);
            }

            if (filterModel.IsKillLastTwoNumsSum)
            {
                filters += new FilterDelegate(FilterHelper.KillLastTwoNumsSum);
            }

            return filters;
        }

        private void DisplayResult()
        {
            if (!string.IsNullOrEmpty(path))
            {
                string savedDatas = "";
                StringBuilder sb = new StringBuilder();
                //读取文件
                using (StreamReader sr = File.OpenText(path))
                {
                    while ((savedDatas = sr.ReadLine()) != null)
                    {
                        sb.Append(savedDatas);
                    }
                }

                var latestData = LotteryData.GetInstance().Lotterys.FirstOrDefault();
                string latestWinnerNumber = latestData.FourDNumber;
                string issue = latestData.Issue;
                //this.tbResult.Dispatcher.Invoke(new Action(delegate()
                //{
                //    this.tbResult.Text = "第" + issue + "期开奖号码：" + latestWinnerNumber + (sb.ToString().Contains(latestWinnerNumber) ? "中奖" : "未中奖");

                //}));
            }

        }

        /// <summary>
        /// 方案一
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rdbFirstSolution_Checked_1(object sender, RoutedEventArgs e)
        {
            HistoricDataHelper.SolutionId = "A";
            solution = 0;
            FilterHelper.SelectedSolution = 0;

            #region v2 方案一:01234(200期）+最冷号  5000注
            //this.chk0123.IsChecked = false;
            //this.chk01234.IsChecked = true;
            //this.cmb01234.Text = "200";
            //this.chbZuiLengHao.IsChecked = true;
            #endregion

            #region
            this.chk012.IsChecked = true;
            this.cmb012.Text = "5";
            this.chk0123.IsChecked = true;
            this.cmb0123.Text = "10";
            this.chk01234.IsChecked = true;
            this.cmb01234.Text = "50";

            this.chbDengZhi.IsChecked = true;
            this.chbDanMa.IsChecked = true;
            this.chbZuiLengHao.IsChecked = true;
            this.chbHotCode.IsChecked = false;

            this.chbHeZhi.IsChecked = true;
            this.chbKuaDuHe.IsChecked = false;
            this.chbLastTwoNumsSubtraction.IsChecked = false;
            this.chbLastTwoNumsSum.IsChecked = false;

            this.chbXiangTongKuaDu.IsChecked = true;
            this.chbShunZhiKuaDu.IsChecked = true;
            this.chbQian200.IsChecked = true;
            this.chbLatestIssue.IsChecked = false;

            this.chkShunzi.IsChecked = true;
            this.chbPositionDifference.IsChecked = true;

            this.chbSmallToBig.IsChecked = true;
            this.chbBigToSmall.IsChecked = true;
            this.chbProduct.IsChecked = true;

            this.chbHSDanMa.IsChecked = true;
            this.chbSmallMiddleBig.IsChecked = true;
            this.chbSQSWDanMa.IsChecked = true;
            this.chbHSDanMa3.IsChecked = false;
            #endregion

        }

        /// <summary>
        /// 方案二
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rdbSecondSolution_Checked_1(object sender, RoutedEventArgs e)
        {
            HistoricDataHelper.SolutionId = "B";
            solution = 1;
            FilterHelper.SelectedSolution = 1;

            #region v2 方案二：01234（500期）+最冷号   7000注
            //this.chk0123.IsChecked = false;
            //this.chk01234.IsChecked = true;
            //this.cmb01234.Text = "500";
            //this.chbZuiLengHao.IsChecked = true;
            #endregion


            #region
            this.chk012.IsChecked = true;
            this.cmb012.Text = "2";
            this.chk0123.IsChecked = true;
            this.cmb0123.Text = "5";
            this.chk01234.IsChecked = true;
            this.cmb01234.Text = "8";

            this.chbDengZhi.IsChecked = false;
            this.chbDanMa.IsChecked = true;
            this.chbZuiLengHao.IsChecked = true;
            this.chbHotCode.IsChecked = false;

            this.chbHeZhi.IsChecked = false;
            this.chbKuaDuHe.IsChecked = false;
            this.chbLastTwoNumsSubtraction.IsChecked = false;
            this.chbLastTwoNumsSum.IsChecked = false;

            this.chbXiangTongKuaDu.IsChecked = false;
            this.chbShunZhiKuaDu.IsChecked = false;
            this.chbQian200.IsChecked = true;

            this.chkShunzi.IsChecked = true;
            this.chbPositionDifference.IsChecked = false;

            this.chbSmallToBig.IsChecked = true;
            this.chbBigToSmall.IsChecked = true;
            this.chbProduct.IsChecked = true;

            this.chbLatestIssue.IsChecked = false;
            this.chbHSDanMa.IsChecked = false;
            this.chbSmallMiddleBig.IsChecked = false;
            this.chbSQSWDanMa.IsChecked = false;
            this.chbHSDanMa3.IsChecked = false;
            #endregion

            #region history
            //this.chk012.IsChecked = false;
            //this.cmb012.Text = "30";
            //this.chk0123.IsChecked = false;
            //this.cmb0123.Text = "10";
            //this.chk01234.IsChecked = true;
            //this.cmb01234.Text = "50";

            //this.chbDengZhi.IsChecked = true;
            //this.chbDanMa.IsChecked = true;
            //this.chbZuiLengHao.IsChecked = true;
            //this.chbHotCode.IsChecked = true;

            //this.chbHeZhi.IsChecked = false;
            //this.chbKuaDuHe.IsChecked = false;
            //this.chbLastTwoNumsSubtraction.IsChecked = false;
            //this.chbLastTwoNumsSum.IsChecked = false;

            //this.chbXiangTongKuaDu.IsChecked = true;
            //this.chbShunZhiKuaDu.IsChecked = true;
            //this.chbQian200.IsChecked = true;

            //this.chkShunzi.IsChecked = true;
            //this.chbPositionDifference.IsChecked = true;

            //this.chbSmallToBig.IsChecked = true;
            //this.chbBigToSmall.IsChecked = true;
            //this.chbProduct.IsChecked = true;

            //this.chbLatestIssue.IsChecked = false;
            //this.chbHSDanMa.IsChecked = false;
            //this.chbSmallMiddleBig.IsChecked = false;
            //this.chbSQSWDanMa.IsChecked = false;
            //this.chbHSDanMa3.IsChecked = false;
            #endregion
        }

        /// <summary>
        /// 方案三
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rdbThirdSolution_Checked_1(object sender, RoutedEventArgs e)
        {
            HistoricDataHelper.SolutionId = "C";
            solution = 2;
            FilterHelper.SelectedSolution = 2;

            #region v2 方案三：0123（150期）+01234（500期）+最冷号  8500注
            //this.chk0123.IsChecked = true;
            //this.cmb0123.Text = "150";
            //this.chk01234.IsChecked = true;
            //this.cmb01234.Text = "500";
            //this.chbZuiLengHao.IsChecked = true;
            #endregion

            #region v1
            this.chk012.IsChecked = false;
            this.cmb012.Text = "30";
            this.chk0123.IsChecked = false;
            this.cmb0123.Text = "10";
            this.chk01234.IsChecked = false;
            this.cmb01234.Text = "200";

            this.chbDengZhi.IsChecked = false;//豹子号
            this.chbDanMa.IsChecked = false;//胆码
            this.chbZuiLengHao.IsChecked = true;//最冷号
            this.chbHotCode.IsChecked = false;
            this.chbHeZhi.IsChecked = true;
            this.chbKuaDuHe.IsChecked = true;
            this.chbLastTwoNumsSubtraction.IsChecked = false;
            this.chbLastTwoNumsSum.IsChecked = true;

            this.chbXiangTongKuaDu.IsChecked = false;
            this.chbShunZhiKuaDu.IsChecked = false;
            this.chbQian200.IsChecked = false;

            this.chkShunzi.IsChecked = false;
            this.chbPositionDifference.IsChecked = false;

            this.chbSmallToBig.IsChecked = false;
            this.chbBigToSmall.IsChecked = false;
            this.chbProduct.IsChecked = false;

            this.chbLatestIssue.IsChecked = false;
            this.chbHSDanMa.IsChecked = true;
            this.chbSmallMiddleBig.IsChecked = false;
            this.chbSQSWDanMa.IsChecked = false;
            this.chbHSDanMa3.IsChecked = true;
            #endregion
        }

        void SetAverageDatasToEachTextBox(string allDatas, string strCount)
        {
            lblDataCount.Dispatcher.BeginInvoke(new Action(delegate() { this.lblDataCount.Content = strCount; }));

            string[] array = allDatas.Split(',');

            int len = array.Length;
            int avg = len / 10;
            int b = len % 10;

            StringBuilder sb1 = new StringBuilder();
            StringBuilder sb2 = new StringBuilder();
            StringBuilder sb3 = new StringBuilder();
            StringBuilder sb4 = new StringBuilder();
            StringBuilder sb5 = new StringBuilder();
            StringBuilder sb6 = new StringBuilder();
            StringBuilder sb7 = new StringBuilder();
            StringBuilder sb8 = new StringBuilder();
            StringBuilder sb9 = new StringBuilder();
            StringBuilder sb10 = new StringBuilder();

            for (int i = 0; i < len; i++)
            {
                if (i < avg * 1)
                {
                    sb1.Append(array[i] + ",");
                }
                else if (i >= avg * 1 && i < avg * 2)
                {
                    sb2.Append(array[i] + ",");
                }
                else if (i >= avg * 2 && i < avg * 3)
                {
                    sb3.Append(array[i] + ",");
                }
                else if (i >= avg * 3 && i < avg * 4)
                {
                    sb4.Append(array[i] + ",");
                }
                else if (i >= avg * 4 && i < avg * 5)
                {
                    sb5.Append(array[i] + ",");
                }
                else if (i >= avg * 5 && i < avg * 6)
                {
                    sb6.Append(array[i] + ",");
                }
                else if (i >= avg * 6 && i < avg * 7)
                {
                    sb7.Append(array[i] + ",");
                }
                else if (i >= avg * 7 && i < avg * 8)
                {
                    sb8.Append(array[i] + ",");
                }
                else if (i >= avg * 8 && i < avg * 9)
                {
                    sb9.Append(array[i] + ",");
                }
                else if (i >= avg * 9 && i < len)
                {
                    sb10.Append(array[i] + ",");
                }
            }

            this.txtData1.Dispatcher.Invoke(new Action(delegate() { this.txtData1.Text = sb1.ToString(); }));
            this.txtData2.Dispatcher.Invoke(new Action(delegate() { this.txtData2.Text = sb2.ToString(); }));
            this.txtData3.Dispatcher.Invoke(new Action(delegate() { this.txtData3.Text = sb3.ToString(); }));
            this.txtData4.Dispatcher.Invoke(new Action(delegate() { this.txtData4.Text = sb4.ToString(); }));
            this.txtData5.Dispatcher.Invoke(new Action(delegate() { this.txtData5.Text = sb5.ToString(); }));
            this.txtData6.Dispatcher.Invoke(new Action(delegate() { this.txtData6.Text = sb6.ToString(); }));
            this.txtData7.Dispatcher.Invoke(new Action(delegate() { this.txtData7.Text = sb7.ToString(); }));
            this.txtData8.Dispatcher.Invoke(new Action(delegate() { this.txtData8.Text = sb8.ToString(); }));
            this.txtData9.Dispatcher.Invoke(new Action(delegate() { this.txtData9.Text = sb9.ToString(); }));
            this.txtData10.Dispatcher.Invoke(new Action(delegate() { this.txtData10.Text = sb10.ToString(); }));
        }

        #region Buttons

        private void btnData1_Click_1(object sender, RoutedEventArgs e)
        {
            //txtData1.Background = new SolidColorBrush(Colors.LawnGreen);
            this.txtData1.SelectAll();
            this.txtData1.Cut();
        }

        private void btnData2_Click(object sender, RoutedEventArgs e)
        {
            //txtData2.Background = new SolidColorBrush(Colors.LawnGreen);
            this.txtData2.SelectAll();
            this.txtData2.Cut();
        }

        private void btnData3_Click(object sender, RoutedEventArgs e)
        {
            //txtData3.Background = new SolidColorBrush(Colors.LawnGreen);
            this.txtData3.SelectAll();
            this.txtData3.Cut();
        }

        private void btnData4_Click(object sender, RoutedEventArgs e)
        {
            //txtData4.Background = new SolidColorBrush(Colors.LawnGreen);
            this.txtData4.SelectAll();
            this.txtData4.Cut();
        }

        private void btnData5_Click(object sender, RoutedEventArgs e)
        {
            //txtData5.Background = new SolidColorBrush(Colors.LawnGreen);
            this.txtData5.SelectAll();
            this.txtData5.Cut();
        }

        private void btnData6_Click(object sender, RoutedEventArgs e)
        {
            //txtData6.Background = new SolidColorBrush(Colors.LawnGreen);
            this.txtData6.SelectAll();
            this.txtData6.Cut();
        }

        private void btnData7_Click(object sender, RoutedEventArgs e)
        {
            //txtData7.Background = new SolidColorBrush(Colors.LawnGreen);
            this.txtData7.SelectAll();
            this.txtData7.Cut();
        }

        private void btnData8_Click(object sender, RoutedEventArgs e)
        {
            //txtData8.Background = new SolidColorBrush(Colors.LawnGreen);
            this.txtData8.SelectAll();
            this.txtData8.Cut();
        }

        private void btnData9_Click(object sender, RoutedEventArgs e)
        {
            //txtData9.Background = new SolidColorBrush(Colors.LawnGreen);
            this.txtData9.SelectAll();
            this.txtData9.Cut();
        }

        private void btnData10_Click(object sender, RoutedEventArgs e)
        {
            //txtData10.Background = new SolidColorBrush(Colors.LawnGreen);
            this.txtData10.SelectAll();
            this.txtData10.Cut();
        }

        #endregion


    }

    delegate void FilterDelegate(LotteryModel lottery);
}
